package com.fh.controller.expand;

import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fh.controller.base.BaseController;
import com.fh.entity.AppUser;
import com.fh.entity.Event;
import com.fh.entity.EventComment;
import com.fh.entity.Page;
import com.fh.entity.PlanContent;
import com.fh.entity.system.Dictionaries;
import com.fh.util.AppUtil;
import com.fh.util.ObjectExcelView;
import com.fh.util.Const;
import com.fh.util.Constants;
import com.fh.util.PageData;
import com.fh.util.Jurisdiction;
import com.fh.service.expand.EventCommentService;
import com.fh.service.expand.EventService;
import com.fh.service.expand.PlanContentService;
import com.fh.service.system.appuser.AppuserService;
import com.fh.service.system.dictionaries.DictionariesService;

/** 
 * 类名称：EventController
 * 创建人：FH 
 * 创建时间：2017-08-10
 */
@Controller
@RequestMapping(value="/event")
public class EventController extends BaseController {
	String menuUrl = "event/list.do"; //菜单地址(权限用)
	@Resource(name="eventService")
	private EventService eventService;
	@Resource(name="planContentService")
	private PlanContentService planContentService;
	@Resource
	private AppuserService appUserService;
	@Resource
	private EventCommentService eventCommentService;
	@Resource
	private DictionariesService dictionariesService;
	/**
	 * 新增突发事件
	 */
	@RequestMapping(value="/submit",method = {RequestMethod.GET,RequestMethod.POST})
	public String submitEvent(Event event,ModelMap modelMap) throws Exception{
		logger.info("<<<<<<<<<<<<<传入submitEvent中的Event对象 : " + event.toString());
		logBefore(logger, "submitEvent");
//		if(!Jurisdiction.buttonJurisdiction(menuUrl, "add")){return null;} //校验权限
//		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		String loginKey = pd.getString("loginKey");//取出当前登陆人
		
		AppUser appUser = appUserService.findByToken(loginKey);
		logger.info("上报事件人的id : " + appUser.getUserId());
		pd.put("publisherId", appUser.getUserId());//当前事件的发布人
		eventService.save(pd);
		modelMap.put("result", 1);
		modelMap.remove("event");
//		mv.addObject("msg","success");
//		mv.setViewName("save_result");
		return "";
	}
	
	
	/**
	 * 为突发事件追加信息
	 */
	@RequestMapping(value="/submitEventComment",method = {RequestMethod.GET,RequestMethod.POST})
	public @ResponseBody Object submitEventComment(EventComment eventComment,String loginKey) throws Exception{
		logger.info("<<<<<<<<<<<<<传入submitEventComment中的EventComment对象 : " + eventComment.toString());
//		logBefore(logger, "submitEventComment");
		Map<String,Object> map = new HashMap<>();
		if(StringUtils.isEmpty(loginKey)){
			map.put("result", Constants.FAIL);
			map.put("errorMsg", "LoginKey is Empty");
		}else{
			AppUser appUser = appUserService.findByToken(loginKey);
			Long id = eventComment.getEventId();//事件id
			String commentReceiverId = eventComment.getReceiverId();//评论的接收人列表
			Event event = eventService.findById1(id);//拿到事件
			
			/*将评论的接收人加入事件的接收人中*/
			if(event != null && !StringUtils.isEmpty(commentReceiverId)){
				String receiverId = event.getReceiverId();
				logger.info("事件原本的接收人 : " + receiverId);
				String[] strArr = commentReceiverId.split(",");
				for(int i = 0; i < strArr.length; i++){
					String strReceiver = strArr[i];
//					if(!receiverId.contains(strReceiver)){
						if(!StringUtils.isEmpty(receiverId)){
							receiverId = receiverId + "," + strReceiver;
						}else{
							receiverId = strReceiver;
						}
//					}
				}
				logger.info("即将修改时的接收人 : " + receiverId);
				event.setReceiverId(receiverId);
				int editFlag = eventService.edit(event);
				logger.info("将评论中的接收人追加到事件中更新时，更新结果是 : " + editFlag);
			}
			/*将评论的接收人加入事件的接收人中  end*/
			
			
			eventComment.setCreateTime(new Date());
			eventComment.setUserId(appUser.getUserId());
			
			logger.info("传入的eventComment经过构造后保存之前的详细情况 ： " + eventComment.toString());
			int insertId = eventCommentService.saveEventComment(eventComment);//插入成功返回主键
			if(insertId > 0){
				map.put("result", Constants.SUCCESS);
			}else{
				map.put("result", Constants.FAIL);
				map.put("errorMsg", "eventComment is InValid");
			}
		}
		
		
		return map;
	}
	
	/**
	 * 新增
	 */
	@RequestMapping(value="/save")
	public ModelAndView save() throws Exception{
		logBefore(logger, "新增Event");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "add")){return null;} //校验权限
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("EVENT_ID", this.get32UUID());	//主键
		pd.put("TITLE", "''");	//标题
		pd.put("PROPERTYLOSS", "1");	//财产损失 1代表1-1000,2代表1001-3000,3代表3001-5000,4代表5001-10000，5代表10000以上
		pd.put("PEOPLELOSS", "1");	//人员伤亡(1代表1-5,2代表6-10,3代表10以上)
		eventService.save(pd);
		mv.addObject("msg","success");
		mv.setViewName("save_result");
		return mv;
	}
	
	/**
	 * 修改
	 */
//	@RequestMapping(value="/edit")
//	public ModelAndView edit() throws Exception{
//		logBefore(logger, "修改Event");
//		if(!Jurisdiction.buttonJurisdiction(menuUrl, "edit")){return null;} //校验权限
//		ModelAndView mv = this.getModelAndView();
//		PageData pd = new PageData();
//		pd = this.getPageData();
//		eventService.edit(pd);
//		mv.addObject("msg","success");
//		mv.setViewName("save_result");
//		return mv;
//	}
	
	/**
	 * 删除
	 */
	@RequestMapping(value="/delete")
	public void delete(PrintWriter out){
		logBefore(logger, "删除Event");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "del")){return;} //校验权限
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			eventService.delete(pd);
			out.write("success");
			out.close();
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		
	}


	/**
	 * 列表
	 * @throws Exception 
	 */
	@RequestMapping(value="/list",method = {RequestMethod.GET,RequestMethod.POST})
	public @ResponseBody Object list(Page page) throws Exception{
		logBefore(logger, "列表Event");
		//if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")){return null;} //校验权限
		Map<String,Object> map = new HashMap<>();
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		
		try{
			pd = this.getPageData();
			
			String loginKey = pd.getString("loginKey");//取出当前登陆人
			AppUser appUser = appUserService.findByToken(loginKey);
			
			pd.put("userId", appUser.getUserId());//以便后续根据receiver_id进行过滤的时候判断用
			page.setPd(pd);
			logger.info("放入page中的pd的userId : " + page.getPd().getString("userId"));
			List<Event>	eventList = eventService.list(page);	//列出Event列表
			List<PageData> returnList = new ArrayList<>();
			
			if(eventList != null && eventList.size() > 0){
				for(Event e : eventList){
					PageData pdEvent = this.convertBeanToPageData(e);
					String eventTypeId = e.getEventTypeId();//事件类型id
					if(!StringUtils.isEmpty(eventTypeId)){
						Dictionaries dicEventType = dictionariesService.findById1(eventTypeId);
						pdEvent.put("eventTypeStr", dicEventType == null ? "无" : dicEventType.getName());
					}else{
						pdEvent.put("eventTypeStr", "无");
					}
					
					returnList.add(pdEvent);
				}
			}
			
			mv.setViewName("expand/event/event_list");
			mv.addObject("varList", eventList);
			mv.addObject("pd", pd);
			mv.addObject(Const.SESSION_QX,this.getHC());	//按钮权限
			map.put("result", Constants.SUCCESS);
			map.put("list", returnList);
			map.put("page", page);
		} catch(Exception e){
			logger.error(e.toString(), e);
			map.put("result", Constants.FAIL);
		}
		return map;
	}
	
	/**
	 * 详情
	 */
	@RequestMapping(value="/detail",method = {RequestMethod.GET,RequestMethod.POST})
	public @ResponseBody Object detail (@RequestParam(value="id",required=false) Long id) throws Exception{
		logBefore(logger, "event/detail");
		if(id == null){
			throw new NullPointerException("event的id不能为空");
		}
		//if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")){return null;} //校验权限
		Map<String,Object> map = new HashMap<>();
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			
			Event event =  eventService.findById(pd);
			List<AppUser> appUserList = new ArrayList<>();//保存接收人的list
			List<EventComment> eventCommentList = new ArrayList<>();//保存评论list
			if(event != null){
			
				PageData pdEvent = this.convertBeanToPageData(event);//转换为PageData对象
				List<PageData> commentList = new ArrayList<>();//存储评论的list
				String receiverId = event.getReceiverId();//事件接收人id
				String eventTypeId = event.getEventTypeId();//事故类型id
				String publisherId = event.getPublisherId();//发布人id
				/*添加事件类型具体值*/
				if(!StringUtils.isEmpty(eventTypeId)){
					Dictionaries dic = dictionariesService.findById1(eventTypeId);
					if(dic != null){
						pdEvent.put("eventTypeStr", dic.getName());
					}else{
						pdEvent.put("eventTypeStr", "无");
					}
				}else{
					pdEvent.put("eventTypeStr", "无");
				}
				/*添加事件类型具体值  end*/
				
				/*添加事件发布人具体值*/
				if(!StringUtils.isEmpty(publisherId)){
					AppUser publishUser = appUserService.findByUiId1(publisherId);
					if(publishUser != null){
						pdEvent.put("publisherName", publishUser.getUserName());
						pdEvent.put("puhlisherAvatar", publishUser.getAvatar());
					}else{
						pdEvent.put("publisherName", "无 ");
						pdEvent.put("puhlisherAvatar", "无");
					}
				}else{
					pdEvent.put("publisherName", "无 ");
					pdEvent.put("puhlisherAvatar", "无");
				}
				/*添加事件发布人具体值  end*/
				
				logger.info("当前事件的接收人都有 : " + receiverId);
				if(receiverId != null){
					String[] userIdArray = receiverId.split(",");
					for(String userId : userIdArray){
						logger.info("当前循环查询的用户id : " + userId);
						AppUser appUser= appUserService.findByUiId1(userId);
						if(appUser != null){
							appUserList.add(appUser);
						}
					}
				}
				List<AppUser> commentUserList = new ArrayList<>();//保存评论接收人的list
				eventCommentList = eventCommentService.listEventCommentByEventId(event.getId());
				logger.info("当前事件的评论一共有 : " + eventCommentList.size());
				if(eventCommentList != null){
					for(EventComment comment : eventCommentList){
						PageData commentPd = this.convertBeanToPageData(comment);
						String userId = comment.getUserId();//评论人id
						AppUser appUser = appUserService.findByUiId1(userId);//评论人
						String commentReceiverId = comment.getReceiverId();//当前评论的可见人
						if(commentReceiverId != null){
							String[] userIdArray = commentReceiverId.split(",");
							for(String currUserId : userIdArray){
								logger.info("当前循环查询的用户id : " + userId);
								AppUser currUser= appUserService.findByUiId1(currUserId);
								if(currUser != null){
									commentUserList.add(currUser);
								}
							}
						}
						if(appUser != null){
							commentPd.put("avatar", appUser.getAvatar());//评论人头像
							commentPd.put("userName", appUser.getUserName());
						}else{
							commentPd.put("userName", "无");
							commentPd.put("avatar", "无");//评论人头像
						}
//						commentPd.put("list", commentUserList);
						commentList.add(commentPd);
					}
				}
				
				logger.info("事件接收人数量 : " + appUserList.size());
				logger.info("评论接收人数量 : " + commentUserList.size());
				List<AppUser> returnUserList = new ArrayList<>();
				Set<AppUser> returnSet = new HashSet<>();
				
				returnSet.addAll(appUserList);
				returnSet.addAll(commentUserList);
				returnUserList.addAll(returnSet);
				if(returnUserList != null && returnUserList.size() > 0){
					/*排序*/
//					Collections.sort(returnUserList, new Comparator<AppUser>() {
//
//						@Override
//						public int compare(AppUser o1, AppUser o2) {
//							// TODO Auto-generated method stub
//							return o2.getUserId().compareTo(o1.getUserId());
//						}
//						
//					});
				}
				
				map.put("result", Constants.SUCCESS);
				map.put("data", pdEvent);
				map.put("users", returnUserList);
				map.put("comment", commentList);
			}else{
				map.put("result", Constants.SUCCESS);
				map.put("data", event);
				map.put("users", appUserList);
				map.put("comment", eventCommentList);
			}
			
		} catch(Exception e){
			logger.error(e.toString(), e);
			map.put("result", Constants.FAIL);
			map.put("errorMsg", "系统错误");
		}
		return map;
	}
	
	/**
	 * 去新增页面
	 */
	@RequestMapping(value="/goAdd")
	public ModelAndView goAdd(){
		logBefore(logger, "去新增Event页面");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			mv.setViewName("expand/event/event_edit");
			mv.addObject("msg", "save");
			mv.addObject("pd", pd);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}						
		return mv;
	}	
	
	/**
	 * 去修改页面
	 */
	@RequestMapping(value="/goEdit")
	public ModelAndView goEdit(){
		logBefore(logger, "去修改Event页面");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
//			pd = eventService.findById(pd);	//根据ID读取
			Event pd1 = eventService.findById(pd);	//根据ID读取
			mv.setViewName("expand/event/event_edit");
			mv.addObject("msg", "edit");
			mv.addObject("pd", pd1);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}						
		return mv;
	}	
	
	/**
	 * 批量删除
	 */
	@RequestMapping(value="/deleteAll")
	@ResponseBody
	public Object deleteAll() {
		logBefore(logger, "批量删除Event");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "dell")){return null;} //校验权限
		PageData pd = new PageData();		
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			pd = this.getPageData();
			List<PageData> pdList = new ArrayList<PageData>();
			String DATA_IDS = pd.getString("DATA_IDS");
			if(null != DATA_IDS && !"".equals(DATA_IDS)){
				String ArrayDATA_IDS[] = DATA_IDS.split(",");
				eventService.deleteAll(ArrayDATA_IDS);
				pd.put("msg", "ok");
			}else{
				pd.put("msg", "no");
			}
			pdList.add(pd);
			map.put("list", pdList);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			logAfter(logger);
		}
		return AppUtil.returnObject(pd, map);
	}
	
	/*
	 * 导出到excel
	 * @return
	 */
	@RequestMapping(value="/excel")
	public ModelAndView exportExcel(){
		logBefore(logger, "导出Event到excel");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")){return null;}
		ModelAndView mv = new ModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try{
			Map<String,Object> dataMap = new HashMap<String,Object>();
			List<String> titles = new ArrayList<String>();
			titles.add("标题");	//1
			titles.add("创建时间");	//2
			titles.add("发生时间");	//3
			titles.add("财产损失 1代表1-1000,2代表1001-3000,3代表3001-5000,4代表5001-10000，5代表10000以上");	//4
			titles.add("人员伤亡(1代表1-5,2代表6-10,3代表10以上)");	//5
			titles.add("发展趋势描述");	//6
			titles.add("其他");	//7
			titles.add("省");	//8
			titles.add("市");	//9
			titles.add("区");	//10
			titles.add("街道");	//11
			titles.add("图片");	//12
			titles.add("接收人id");	//13
			titles.add("事故类型id");	//14
			dataMap.put("titles", titles);
//			List<PageData> varOList = eventService.listAll(pd);
			List<Event> varOList = eventService.listAll(pd);
			List<PageData> varList = new ArrayList<PageData>();
			for(int i=0;i<varOList.size();i++){
				PageData vpd = new PageData();
//				vpd.put("var1", varOList.get(i).getString("TITLE"));	//1
//				vpd.put("var2", varOList.get(i).getString("CREATETIME"));	//2
//				vpd.put("var3", varOList.get(i).getString("HAPPENEDTIME"));	//3
//				vpd.put("var4", varOList.get(i).get("PROPERTYLOSS").toString());	//4
//				vpd.put("var5", varOList.get(i).get("PEOPLELOSS").toString());	//5
//				vpd.put("var6", varOList.get(i).getString("DEVDESC"));	//6
//				vpd.put("var7", varOList.get(i).getString("OTHER"));	//7
//				vpd.put("var8", varOList.get(i).getString("PROVINCE"));	//8
//				vpd.put("var9", varOList.get(i).getString("CITY"));	//9
//				vpd.put("var10", varOList.get(i).getString("AREA"));	//10
//				vpd.put("var11", varOList.get(i).getString("STREET"));	//11
//				vpd.put("var12", varOList.get(i).getString("PIC"));	//12
//				vpd.put("var13", varOList.get(i).getString("RECEIVERID"));	//13
//				vpd.put("var14", varOList.get(i).getString("EVENTTYPEID"));	//14
				vpd.put("var1", varOList.get(i).getTitle());	//1
				vpd.put("var2", varOList.get(i).getCreateTime());	//2
				vpd.put("var3", varOList.get(i).getHappenedTime());	//3
				vpd.put("var4", varOList.get(i).getPropertyLoss());	//4
				vpd.put("var5", varOList.get(i).getPeopleLoss());	//5
				vpd.put("var6", varOList.get(i).getDevDesc());	//6
				vpd.put("var7", varOList.get(i).getOther());	//7
				vpd.put("var8", varOList.get(i).getProvince());	//8
				vpd.put("var9", varOList.get(i).getCity());	//9
				vpd.put("var10", varOList.get(i).getArea());	//10
				vpd.put("var11", varOList.get(i).getStreet());	//11
				vpd.put("var12", varOList.get(i).getPic());	//12
				vpd.put("var13", varOList.get(i).getReceiverId());	//13
				vpd.put("var14", varOList.get(i).getEventTypeId());	//14
				varList.add(vpd);
			}
			dataMap.put("varList", varList);
			ObjectExcelView erv = new ObjectExcelView();
			mv = new ModelAndView(erv,dataMap);
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	
	/* ===============================权限================================== */
	public Map<String, String> getHC(){
		Subject currentUser = SecurityUtils.getSubject();  //shiro管理的session
		Session session = currentUser.getSession();
		return (Map<String, String>)session.getAttribute(Const.SESSION_QX);
	}
	/* ===============================权限================================== */
	
	@InitBinder
	public void initBinder(WebDataBinder binder){
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(format,true));
	}
	
	
	/**
	 * 列表
	 */
	@RequestMapping(value="/planContent/list",method = {RequestMethod.GET,RequestMethod.POST})
	public @ResponseBody Object planList(Page page){
		logBefore(logger, "planContent列表");
		//if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")){return null;} //校验权限
		Map<String,Object> map = new HashMap<>();
//		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			page.setPd(pd);
			List<PlanContent>	varList = planContentService.listAllPlanContent();
//			mv.addObject("list", varList);
//			mv.addObject("pd", pd);
			map.put("result", Constants.SUCCESS);
			map.put("list", varList);
		} catch(Exception e){
			logger.error(e.toString(), e);
			map.put("result", Constants.FAIL);
		}
		return map;
	}
}
